﻿using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using NetMQ;
using NetMQ.Sockets;

namespace CenterServerDemo
{
    public class SubHandler:ISubHandler
    {
        private ILogger<SubHandler> logger;
        private IPubHandler  pubHandler; 
        private ITopicManager topicManager;
        private ISerializeProvider serializeProvider;
        public SubHandler(ILogger<SubHandler> logger,
            IPubHandler  _pubHandler, 
          ITopicManager _topicManager,
            ISerializeProvider _serializeProvider)
        {
            this.logger = logger; 
            this.topicManager = _topicManager;
            this.serializeProvider = _serializeProvider;
            this.pubHandler = _pubHandler;
        }

        public async Task Handler(NetMQSocket socket,PublisherSocket publisherSocket,string key)
        {
            bool more;
            var topic = socket.ReceiveFrameBytes(out more);
            string s_topic = serializeProvider.Deserialize<string>(topic);
            logger.LogInformation($"topic receive:{s_topic}");
            if (more)
            { 
                byte[] arr_request = null;
                var received = socket.TryReceiveFrameBytes(TimeSpan.FromSeconds(1), out arr_request); 
                var msg = Encoding.UTF8.GetString(arr_request);
                logger.LogInformation($"msg receive:{msg}");
                 
                
                var topicType = await topicManager.GetTopic(key,s_topic);
                if(publisherSocket!=null)
                 await pubHandler.Message(publisherSocket, topicType, msg);


            }

            await Task.CompletedTask;
        }
        
    }
}